package com.newhero.product.common.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.newhero.product.common.constant.BaseConstant;
import com.newhero.product.common.mybatis.plugins.Page;
import com.newhero.product.common.result.Result;
import com.newhero.product.common.shiro.ShiroUser;
import com.newhero.product.common.util.PageInfo;
import com.newhero.product.common.util.StringEscapeEditor;
import com.newhero.product.module.sys.service.IConfigService;
import com.newhero.product.module.sys.model.Blog;
import com.newhero.product.module.sys.service.IBlogService;

/**
 * @ClassName: BaseController 
 * @Description: 基础控制类
 * @author Caolj 648198687@qq.com 
 * @date 2017-3-16 下午3:56:54
 */
public abstract class BaseController implements BaseConstant{
	@Autowired
	private IBlogService blogServiceImpl;

	@Autowired
	private  HttpServletRequest request;

	protected Logger logger = LogManager.getLogger(getClass());
	
	@Autowired
	private IConfigService configServiceImpl;
	@Autowired
	protected HttpServletResponse response;

	
	
	
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        /**
         * 自动转换日期类型的字段格式
         */
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
        /**
         * 防止XSS攻击
         */
        binder.registerCustomEditor(String.class, new StringEscapeEditor());
    }

    /**
     * 获取当前登录用户对象
     * @return {ShiroUser}
     */
    public ShiroUser getShiroUser() {
    	//兼容CAS单点登录
    	Object peincipal = SecurityUtils.getSubject().getPrincipal();
    	if(peincipal instanceof ShiroUser){
    		return (ShiroUser)peincipal;
    	}else{
    		return (ShiroUser) SecurityUtils.getSubject().getSession().getAttribute("shiroUser");
    	}
    }

    /**
     * 获取当前登录用户id
     * @return {Long}
     */
    public String getUserID() {
        return this.getShiroUser().getUserID();
    }

    public String getConfig(String item){
    	return configServiceImpl.getConfigItemValue(item);
    }
    
    public String getConfigWithDefault(String item, String defaultValue){
    	String itemValue = configServiceImpl.getConfigItemValue(item);
    	if(StringUtils.isNotBlank(itemValue)){
    		return itemValue;
    	}else{
    		return defaultValue;
    	}
    }
    
    public String getConfigByRoleId(String item,String roleid){
    	return configServiceImpl.getConfigItemValue(item,roleid);
    }
    
    /**
     * 获取当前登录用户名
     * @return {String}
     */
    public String getUserName() {
        return this.getShiroUser().getUserName();
    }

    /**
     * 获取当前用户所在组织ID
     * @return
     */
    public String getOrganID(){
    	return this.getShiroUser().getOrganID();
    }
    /**
     * 获取当前用户所在组织名称
     * @return
     */
    public String getOrganName(){
    	return this.getShiroUser().getOrganName();
    }
    
    /**
     * ajax失败
     * @param msg 失败的消息
     * @return {Object}
     */
    public Object renderError(String msg) {
        Result result = new Result();
        result.setMsg(msg);
        return result;
    }

    /**
     * ajax成功
     * @return {Object}
     */
    public Object renderSuccess() {
        Result result = new Result();
        result.setSuccess(true);
        return result;
    }

    /**
     * ajax成功
     * @param msg 消息
     * @return {Object}
     */
    public Object renderSuccess(String msg) {
        Result result = new Result();
        result.setSuccess(true);
        result.setMsg(msg);
        return result;
    }

    /**
     * ajax成功
     * @param obj 成功时的对象
     * @return {Object}
     */
    public Object renderSuccess(Object obj) {
        Result result = new Result();
        result.setSuccess(true);
        result.setObj(obj);
        return result;
    }
    
    public <T> Page<T> getPage(int current, int size, String sort, String order){
        Page<T> page = new Page<T>(current, size, sort);
        if ("desc".equals(order)) {
            page.setAsc(false);
        } else {
            page.setAsc(true);
        }
        return page;
    }
    
    public <T> PageInfo pageToPageInfo(Page<T> page) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setRows(page.getRecords());
        pageInfo.setTotal(page.getTotal());
        pageInfo.setOrder(page.getOrderByField());
        return pageInfo;
    }
    
    /**
     * 
     * <li>功能描述：插入blog业务日志表。
     * @param bappName     blogAPPName
     * @param blogContent
     * @param boperType    操作类型，I：新增，U：修改，D：删除，S：查询，UP：上传，DOWN：下载
     * @return
     * Object 
     * @author liangzhuoxin
     */
    public boolean insertBisLog(String appName,String logContent,String operType){
    	try {
    		Blog blog = new Blog();
    		blog.setUserID(getUserID());
    		blog.setUserName(getUserName());
    		Date date=new Date();
    		DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		String nowTime=format.format(date);
    		blog.setBlogTime(nowTime);
    		blog.setBlogIP(getIpAddress(request));
    		System.out.println(getIpAddress(request)+"====="+request.getRemoteAddr());
    		blog.setBappName(appName);
    		blog.setBlogContent(logContent);
    		blog.setBoperType(operType);
			blogServiceImpl.insertOrUpdate(blog);
			return true;
		} catch (Exception e) {
			logger.error(e);
			return false;
		}
    }
    /** 
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址, 
     * 
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？ 
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 
     * 
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130, 
     * 192.168.1.100 
     * 
     * 用户真实IP为： 192.168.1.110 
     * 
     * @param request 
     * @return 
     */
    public static String getIpAddress(HttpServletRequest request) { 
        String ip = request.getHeader("x-forwarded-for"); 
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
          ip = request.getHeader("Proxy-Client-IP"); 
        } 
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
          ip = request.getHeader("WL-Proxy-Client-IP"); 
        } 
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
          ip = request.getHeader("HTTP_CLIENT_IP"); 
        } 
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
          ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 
        } 
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
          ip = request.getRemoteAddr(); 
        } 
        return ip; 
      } 
    
    /**
     * 
     * <li>功能描述：sso重定向。
     * @param url
     * @return
     * String 
     * @author liangzhuoxin
     */
    protected String redirectTo( String url ) {
		StringBuffer rto = new StringBuffer("redirect:");
		rto.append(url);
		return rto.toString();
	}

}
